package com.bjpowernode.p2p.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.bjpowernode.common.constant.Constants;

import com.bjpowernode.p2p.mapper.loan.BidInfoMapper;
import com.bjpowernode.p2p.mapper.loan.LoanInfoMapper;
import com.bjpowernode.p2p.mapper.user.FinanceAccountMapper;
import com.bjpowernode.p2p.model.loan.LoanInfo;
import com.bjpowernode.p2p.model.user.FinanceAccount;
import com.bjpowernode.p2p.model.vo.Page;
import com.bjpowernode.p2p.service.LoanService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@Component
@Service(interfaceName ="com.bjpowernode.p2p.service.LoanService",version ="1.0-SNAPSHOT",timeout = 15000)
public class LoanServiceImpl implements LoanService {

    @Autowired
    private LoanInfoMapper loanInfoMapper;
    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;
    @Autowired
    private FinanceAccountMapper financeAccountMapper;
    @Autowired
    private BidInfoMapper bidInfoMapper;
    @Override
    public Double queryHistoryAvgRate() {
        //先查询redis是否有值，
        Double historyAvgRate = (Double) redisTemplate.opsForValue().get(Constants.HISTORY_AVG_RATE);
        if(!ObjectUtils.allNotNull(historyAvgRate)){//redis没有值：如果为空：取反
            //进行数据库数据查询
            historyAvgRate = loanInfoMapper.selectHistoryAvgRate();
            //将数据库查询获取的值存到redis中,如期：七天更新一次
    redisTemplate.opsForValue().set(Constants.HISTORY_AVG_RATE,historyAvgRate,7, TimeUnit.DAYS);
        }
        return historyAvgRate;
    }

    /**
     * 首页展示各个产品
     * @param pType
     * @return
     */
    @Override
    public List<LoanInfo> queryLoanInfo(Integer pType) {

        return loanInfoMapper.selectLoanInfo(pType);
    }

    @Override
    public Page queryLoanInfoByPage(int pType, String currentPage) {
        if(!ObjectUtils.allNotNull(currentPage)){
            currentPage ="1";
        }
        //查询总记录数
        Integer totalRows = loanInfoMapper.selectTotalRowsByPtype(pType);
        //每页展示的记录数
        //如果不变动，直接在sql 语句中固定了，
        Integer pageSize =9;
        //总页数
        Integer totalPage =(totalRows-1)/pageSize+1;
        //查询当前页数据的起始索引
        int indexLimit =(Integer.parseInt(currentPage)-1)*pageSize;
        //当前页的数据:
        List<LoanInfo> pageData = loanInfoMapper.selectCurrentPageData(pType, pageSize, indexLimit);
        Page<LoanInfo> pageInfo = new Page<>();
        pageInfo.setCurrentPage(currentPage);
        pageInfo.setPageData(pageData);
        pageInfo.setTotalRows(totalRows);
        pageInfo.setTotalPageSize(totalPage);

        return pageInfo;

    }

    /**
     * 查询指定产品loaninfo
     * @param ptype 产品类型
     * @param id 要进行投资的产品id
     * @return
     */
    @Override
    public LoanInfo queryLoanInfoByTypeandId(String ptype, String id) {

        return  loanInfoMapper.selectLoanInfoByTypeAndId(ptype,id);
    }



    @Override
    public LoanInfo queryLoanInfoId(Integer loanId) {
        return loanInfoMapper.selectByPrimaryKey(loanId);
    }

    @Transactional
    @Override
    public int invest(Map<String, Object> paramMap) {
        //开启事务，开启线程
        //修改金融账户
        int result =0;
        result = financeAccountMapper.updateFinanceAva(paramMap);
        //修改产品可投资金额
       // int i =10/0;  开启事务后，如果在执行过程中，有一处报错，则都会不提交任何事务
        //只有有异常，所有事务都要自动回滚！
        result = loanInfoMapper.updateLoanInfoAvarialeMonry(paramMap);
        //添加投资信息表
        String date = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date());
        paramMap.put("bidTime",date);
        paramMap.put("bidStatus",1);
        result = bidInfoMapper.insertInvestRecord(paramMap);
        return result;
    }
}
